package softswitch.service;

import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import softswitch.model.CallLog;
import softswitch.model.Circuit;

@Stateless
public class CallLogDAO {

	@PersistenceContext(unitName = "persistence")
    private EntityManager em;
		
	
	public CallLog getById(Integer id){	
		return em.find(CallLog.class, id);
	}
	
	public CallLog save(CallLog CallLog) {
    	em.persist(CallLog);
    	return CallLog;
    }
	
	public CallLog update(CallLog CallLog) {
    	return em.merge(CallLog);
    }
    
	public void delete(Integer id) {
    	em.remove(em.find(CallLog.class, id));	
    }
    
    //----------------------------------------------------------------------
    
	public void deleteByCircuit(Circuit circuit) {	
    	Query query = em.createQuery("DELETE FROM CallLog e WHERE e.circuit=:circuit");
    	query.setParameter("circuit", circuit);
        query.executeUpdate();   
    }
	
	public void deleteByCircuitDate(Circuit circuit, Date date) {	
    	Query query = em.createQuery("DELETE FROM CallLog e WHERE e.circuit=:circuit AND e.date=:date");
    	query.setParameter("circuit", circuit);
    	query.setParameter("date", date);
        query.executeUpdate();   
    }
	
    @SuppressWarnings("unchecked")
    public List<CallLog> listByCircuitDestination(Circuit circuit,String destination, Date startdate) {
    	
    	String sql;
		sql = " SELECT e FROM CallLog e WHERE e.circuit=:circuit AND e.processdate>:processdate ";

		if(destination!=null){		
			sql = sql + " AND e.destination=:destination ";		
		}

		sql = sql + " ORDER BY e.processdate DESC ";

		Query query = em.createQuery(sql);
		query.setParameter("circuit", circuit);
		query.setParameter("processdate", startdate);
		
		if(destination!=null){		
			query.setParameter("destination", destination);
		}  	
        return query.getResultList();   

    }
  
    
}
